<template>
  <div class="page-box">
    <SearchForm type="array" @search="searchHandler" @reset="resetHandler" />
    <!-- 提取时间选择器 -->
    <ThisDate @change="dateChange" />
    <div class="__content-main">
      <div class="__content-header">
        <img :src="imageUrl" />
        能源成本及用量
      </div>
      <div class="__content-box">
         <div class="chart-container bordered">
          <div class="chart-title analysis-title">
            <span>科室分析</span>
          </div>
          <div class="chart-chart" id="chart4" style="margin-top: 12px;"></div>
        </div>
        <div class="chart-container bordered" v-show="searchParam?.unit?.length">
          <div class="chart-title">产线分析</div>
          <div class="chart-chart" id="chart2"></div>
        </div>
       
        <div class="chart-container bordered  grid-2" v-show="searchParam?.device">
          <div class="chart-title analysis-title">
            <span>设备分析</span>
            <a-select v-model:value="currentType" style="width: 400px;" mode="multiple" :maxTagCount="3" allowClear>
              <a-select-option :value="item.value" v-for="(item, index) in analysisOptions" :key="index">{{item.label}}</a-select-option>
            </a-select>
          </div>
          <div class="chart-chart" id="chart3" style="margin-top: 12px;"></div>
        </div>
        
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import Icon from '@/components/Icon/Icon.vue';
import SearchForm from '../component/searchForm.vue';
import ThisDate from '../component/date.vue';
import useLine from '../useLine';
import useData from '../useData';
import { reactive, ref, onBeforeUnmount, computed, watch, Ref } from 'vue';
import dayjs from 'dayjs';

const imageUrl = new URL('@/assets/svg/table-icon.svg', import.meta.url).href;
const searchParam = ref<any>(null);
const dateEnergy = ref({
  dateType: 'month',
  date: dayjs().format('YYYY-MM-DD'),
  dateRange: [dayjs(), dayjs()]
})
const dateProductionLine = ref({
  dateType: 'month',
  date: dayjs().format('YYYY-MM-DD'),
  dateRange: [dayjs(), dayjs()]
})
const dateDevice = ref({
  dateType: 'month',
  date: dayjs().format('YYYY-MM-DD'),
  dateRange: [dayjs(), dayjs()]
})
const dateClassData = ref({
  dateType: 'month',
  date: dayjs().format('YYYY-MM-DD'),
  dateRange: [dayjs(), dayjs()]
})
const dateUnit = ref({
  dateType: 'month',
  date: dayjs().format('YYYY-MM-DD'),
  dateRange: [dayjs(), dayjs()]
})
const currentType = ref([])

// 确保每次搜索前重置数据
const data = useData({
  energyType: 'array',
  dateEnergy,
  dateProductionLine,
  dateDevice,
  dateUnit,
  searchParam,
  dateClassData
});
let analysisOptions:Ref<any[]> = ref([])
watch(() => data.data['device'], () => {
  let options:any[] = []
  currentType.value = []
  data.data['device']?.yaxisList?.forEach(item => {
    if(!options.find(op => item.name.split('-')[1].indexOf(op.label) > -1)) {
      options.push({
        label: item.name.split('-')[1],
        value: item.name.split('-')[1]
      })
      currentType.value.push(item.name.split('-')[1])
    }
  })
  analysisOptions.value = options
})
// 存储图表实例，以便手动清理
const chartInstances = ref<{ [key: string]: echarts.ECharts | null }>({
  chart2: null,
  chart3: null
});

const dateChange = (value: any) => {
  dateProductionLine.value = value;
  dateDevice.value = value;
  dateClassData.value = value
  setTimeout(() => {
    if (!searchParam.value) return;
    // 更新产线和设备数据前清理图表
    cleanChart('chart2');
    cleanChart('chart3');
    cleanChart('chart4');
    data.getProductionLine();
    data.getDeviceVo();
    data.getClassData()
  }, 200)
}

const searchHandler = (params: any) => {
  searchParam.value = params;
  // 搜索前清理所有图表数据
  cleanAllCharts();

  data.getData();

}

const resetHandler = () => {
  searchParam.value = null;
  // 重置时清理所有图表数据
  cleanAllCharts();
}

// 使用图表时存储实例
const useLineWithInstance = (config: { id: string, data: any, key: string, selectLegendValues?: string[] }) => {
  chartInstances.value[config.id] = useLine({
    ...config,
    // 传递清理函数，便于外部控制
    onClean: () => {
      if (chartInstances.value[config.id]) {
        chartInstances.value[config.id].clear();
      }
    }
  });
}

useLineWithInstance({
  id: 'chart2',
  data: data.data,
  key: 'productionLine',
});
useLineWithInstance({
  id: 'chart3',
  data: data.data,
  key: 'device',
  selectLegendValues: currentType
});
useLineWithInstance({
  id: 'chart4',
  data: data.data,
  key: 'classData',
});
// 清理单个图表
const cleanChart = (id: string) => {
  if (chartInstances.value[id]) {
    chartInstances.value[id].clear();
  }
}

// 清理所有图表
const cleanAllCharts = () => {
  Object.keys(chartInstances.value).forEach(id => {
    cleanChart(id);
  });
}

// 组件卸载时清理资源
onBeforeUnmount(() => {
  cleanAllCharts();
  chartInstances.value = {
    chart2: null,
    chart3: null
  };
});
</script>

<style lang="scss" scoped>
@import url('../style.scss');

.page-box {
  box-sizing: border-box;
  height: 100%;
  padding: 8px;
}

.__content-main {
  height: calc(100% - 72px);
  padding: 8px;
  overflow: hidden;
  background: #fff;
}

.__content-header {
  display: flex;
  position: relative;
  align-items: center;
  min-height: 28px;
  margin-bottom: 8px;
  padding: 0 8px;
  background: #f3f7fb;
  box-shadow: inset 0 1px 3px 0 rgb(0 0 0 / 20%);
  color: #000;
  font-size: 12px;
  font-weight: 600;
  line-height: 20px;
  gap: 8px;
}

.__content-box {
  display: grid;
  grid-gap: 8px;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  height: calc(100% - 36px);
}

.chart-chart {
  position: absolute;
  inset: 0;
}
.grid-2{
  grid-column: span 2;
}
.analysis-title{
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 20px;
  width: 100%;
}
</style>